package com.zhangmeng.online.exam.controller;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.zhangmeng.jwt.dto.LoginUser;
import com.zhangmeng.online.exam.dao.PaperDao;
import com.zhangmeng.online.exam.dao.QuestionDao;
import com.zhangmeng.online.exam.dao.SubjectDao;
import com.zhangmeng.online.exam.dao.UserDao;
import com.zhangmeng.online.exam.dto.Result;
import com.zhangmeng.online.exam.entity.Paper;
import com.zhangmeng.online.exam.entity.Question;
import com.zhangmeng.online.exam.entity.Subject;
import com.zhangmeng.online.exam.entity.User;
import com.zhangmeng.online.exam.utils.PageUtils;
import com.zhangmeng.online.exam.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @author zm
 * @date 2025/3/19 11:10
 * @version: 1.0
 */
@RestController
@RequestMapping("/paper")
public class PaperController {


    @Autowired
    private PaperDao paperDao;

    @Autowired
    private QuestionDao questionDao;

    @Autowired
    private SubjectDao subjectDao;

    @Autowired
    private UserDao userDao;

    @RequestMapping("/list")
    public Result list(Integer pageNum, Integer pageSize) {

        Pageable pageable = PageRequest.of(PageUtils.getPageNum(pageNum), pageSize, Sort.Direction.DESC, "addTime");
        Page<Paper> all = paperDao.findAll(pageable);
        List<Paper> list = all.getContent();
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (Paper paper : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", paper.getId());
            map.put("name", paper.getName());
            map.put("creator_username", paper.getCreator().getUsername());
            map.put("subject_name", paper.getSubject().getName());
            map.put("totalScore", paper.getTotalScore());//总分
            map.put("examTime", paper.getExamTime());//考试时间
            resultList.add(map);
        }
        return Result.success(pageNum, pageSize, all.getTotalElements(), resultList);
    }

    @RequestMapping("/chooseQuestion/save")
    public Result chooseQuestionSave(String id, String ids) {

        Optional<Paper> paperOptional = paperDao.findById(Long.valueOf(id));
        if (!paperOptional.isPresent()){
            return Result.error("试卷不存在");
        }
        Paper paper = paperOptional.get();

        paper.getQuestions().clear();

        for (String questionId : JSONObject.parseArray(ids, String.class)) {
            Optional<Question> question = this.questionDao.findById(Long.valueOf(questionId));
            if (question.isPresent()){
                paper.getQuestions().add(question.get());
            }
        }
        paperDao.save(paper);
        return Result.success(null);
    }

    @RequestMapping("/chooseQuestion/list")
    public Result chooseQuestionList(String id) {
        Optional<Paper> paperOptional = paperDao.findById(Long.valueOf(id));
        if (!paperOptional.isPresent()){
            return Result.error("试卷不存在");
        }
        Paper paper = paperOptional.get();
        List<Question> questions = paper.getQuestions();
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (Question question : questions) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", question.getId());
            map.put("name", question.getName());
            map.put("type", question.getType().getDesc());
            map.put("subject", question.getSubject().getName());
            map.put("score", question.getScore());

            List<Map<String, Object>> list = question.getOptions().stream().map(option -> {
                Map<String, Object> optionMap = new HashMap<>();
                optionMap.put("id", option.getId());
                optionMap.put("name", option.getOptionName());
                optionMap.put("content", option.getOptionContent());
                optionMap.put("score", option.getOptionScore());
                optionMap.put("explanation", option.getExplanation());
                optionMap.put("isAnswer", option.getIsAnswer());
                return optionMap;
            }).toList();

            map.put("options",list );
            resultList.add(map);
        }
        return Result.success(resultList);
    }

    @RequestMapping("/save")
    public Result save(@RequestParam @RequestBody Map<String, Object> params) {

        String id = (String) params.get("id");
        String name = (String) params.get("name");
        String description = (String) params.get("description");
        Integer totalScore = Integer.parseInt( params.get("score").toString());
        Integer passScore = Integer.parseInt( params.get("passScore").toString());
        Integer examTime = Integer.parseInt( params.get("examTime").toString());
        Integer status = Integer.parseInt( params.get("status").toString());
        String subjectId = (String) params.get("subjectId");


        Subject subject = null;
        if (subjectId != null && !subjectId.equals("")){
            subject = this.subjectDao.findById(Long.valueOf(subjectId)).get();
        }

        User creator = this.userDao.getById(UserUtils.getCurrentUserId());


        Paper paper = null;
        if (id != null && !id.isEmpty()){
            paper =  paperDao.getById(Long.valueOf(id));
        }else {
            paper = new Paper();
        }

        paper.setName(name);
        paper.setDescription(description);
        paper.setTotalScore(totalScore);
        paper.setPassScore(passScore);
        paper.setExamTime(examTime);
        paper.setStatus(status);
        paper.setSubject(subject);
        paper.setCreator(creator);
        paperDao.save(paper);

        return Result.success(null);
    }
}
